//
//  BrowseHistoryRow.swift
//  YoruNeko
//
//  Created by  mahoPunch on 2021/6/24.
//

import SwiftUI

struct BrowseHistoryRow: View {
    
    typealias onRowFetch = (_ id: UUID) -> Void?
    
    var history: History
    //let defaultIconData = UIImage(systemName: "clock")?.pngData()
    
    
    @Binding var canRowBeSelected: Bool
    var isSelected: Bool
    
    var onDeleteClickClosure: onRowFetch?
    
    var body: some View {
        HStack {
            
            if let data = history.faviconData, let image = UIImage(data: data) {
                Image(uiImage: image)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 40, height: 25)
            } else {
                Image(systemName: "clock")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 40, height: 25)
            }


            
            VStack(alignment: .leading){
                
                Text(history.title)
                    .lineLimit(1)
                    
                Text(history.url)
                    .font(.footnote)
                    .foregroundColor(Color(.systemGray2))
                    .lineLimit(1)
            }
            Spacer()
            
            if canRowBeSelected{
                Image(systemName: isSelected ? "checkmark.circle" : "circle")
                    .resizable()
                    .frame(width: canRowBeSelected ? CGFloat(20) : CGFloat(0), height: 20, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                    .padding(.trailing, 2)
                    .foregroundColor(.blue)
            }
            else {
                Button(action: {
                    onDeleteClickClosure?(history.id)
                }){
                    Image(systemName: "trash").padding(.trailing, 4)
                }
                .foregroundColor(.red)
            }
            
            
        }
        .padding(.vertical, 2)
    }
}

var test = History(faviconData: (UIImage(systemName: "star")?.pngData())!, date_added: Date(), title: "google4", url: "www.google.com")
    
struct BrowseHistoryRow_Previews: PreviewProvider {
    static var previews: some View {
        BrowseHistoryRow(history: test, canRowBeSelected: .constant(true), isSelected: true)
    }
}
